<?php

namespace api\libs\notifications;

use Yii;
use Exception;
use api\libs\notifications\models\Notification;
use yii\base\Module;
use yii\db\Expression;
use api\components\helpers\Constant;
use api\libs\notifications\models\NotificationTemplate;
use common\models\User;

class NotificationsModule extends Module {

    /**
     * @var string The controllers namespace
     */
    public $controllerNamespace = 'api\libs\notifications\controllers';

    /**
     * @var Notification The notification class defined by the application
     */
    public $notificationClass;

    /**
     * @var boolean Whether notification can be duplicated (same user_id, key, and key_id) or not
     */
    public $allowDuplicate = false;

    /**
     * @var string Database created_at field format
     */
    public $dbDateFormat = 'Y-m-d H:i:s';

    /**
     * @var callable|integer The current user id
     */
    public $userId;

    /**
     * @var callable|integer The current user id
     */
    public $expirationTime = 0;

    /**
     * @inheritdoc
     */
    public function init() {
        if (is_callable($this->userId)) {
            $this->userId = call_user_func($this->userId);
        }
        parent::init();

        if (Yii::$app instanceof \yii\console\Application) {
            $this->controllerNamespace = 'api\modules\notifications\commands';
        }
    }

    /**
     * Creates a notification
     *
     * @param Notification $notification The notification class
     * @param string $key The notification key
     * @param integer $user_id The user id that will get the notification
     * @param string $key_id The key unique id
     * @param string $type The notification type
     * @return bool Returns TRUE on success, FALSE on failure
     * @throws Exception
     */
    public static function notify($notification, $type = Notification::TYPE_DEFAULT, $user_id, $template_name, $params = [], $campaign_id = 0) {
        if (!in_array($type, Notification::$types)) {
            throw new Exception("Unknown notification type: $type");
        }
        if ($type == Notification::TYPE_DEFAULT) {
            $instance = new $notification([
                'type' => $type,
                'is_read' => 0,
                'content' => isset($params['content']) ? $params['content'] : '',
                'template_id' => 0,
                'recipient' => $user_id,
                'ctime' => new Expression('NOW()'),
                'campaign_id' => $campaign_id,
            ]);
            return $instance->save();
        } else if ($type == Notification::TYPE_TEMPLATE) {
            $templates = NotificationTemplate::find()->where(['name' => $template_name, 'status' => Constant::STATUS_VALID])->all();
            $user = User::findOne($user_id);
            if (!empty($templates)) {
                foreach ($templates as $template) {
                    // 站内信
//                    if (in_array($template->type, [NotificationTemplate::TYPE_INBOX, NotificationTemplate::TYPE_SYSTEM_NOTICE, NotificationTemplate::TYPE_UPGRADE_NOTICE])) {
                    if ($template->type == NotificationTemplate::TYPE_INBOX) {
                        $instance = new $notification([
                            'type' => $type,
                            'is_read' => 0,
                            'content' => strtr($template->content, $params),
                            'template_id' => $template->id,
                            'recipient' => $user_id,
                            'ctime' => new Expression('NOW()'),
                            'campaign_id' => $campaign_id,
                        ]);
                        $result = $instance->save();
                        if (!$result) return false;
                    } else if ($template->type == NotificationTemplate::TYPE_EMAIL) {// 邮箱
                        if (!empty($user->email)) {
                            $instance_queue = new models\NotificationQueue([
                                'template_id' => $template->id,
                                'type' => 1,
                                'content' => strtr($template->content, $params),
                                'recipient_uid' => $user_id,
                                'recipient_contact' => $user->email,
                                'ctime' => new Expression('NOW()'),
                                'try' => 3,
                            ]);
                            $result = $instance_queue->save();
                            if (!$result) return false;
                        }
                    } else if ($template->type == NotificationTemplate::TYPE_SMS) {// 短信
                        if (!empty($user->mobile)) {
                            $instance_queue = new models\NotificationQueue([
                                'template_id' => $template->id,
                                'type' => 2,
                                'content' => json_encode($params),
                                'recipient_uid' => $user_id,
                                'recipient_contact' => $user->mobile,
                                'ctime' => new Expression('NOW()'),
                                'try' => 3,
                            ]);
                            $result = $instance_queue->save();
                            if (!$result) return false;
                        }
                    }
                }
            } else {
                throw new Exception("Unknown notification template_id");
            }
        }

        return true;
    }
}
